package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<String> add(@RequestBody ShoppingCart shoppingCart){
        //根据用户ID与setmealid或者dishid来查询这一条数据，（后面两个ID只能存在一个）
        QueryWrapper<ShoppingCart> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("user_id", BaseContext.getCurrentId());
        queryWrapper1.eq(shoppingCart.getDishId()!=null,"dish_id",shoppingCart.getDishId());
        queryWrapper1.eq(shoppingCart.getSetmealId()!=null,"setmeal_id",shoppingCart.getSetmealId());
        ShoppingCart cart = shoppingCartService.getOne(queryWrapper1);
        //根据查询出来的cart，判断是否为null，不是的话数量加一，是的话添加数据
        if(cart==null){
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setNumber(1);

            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }else {
            cart.setNumber(cart.getNumber()+1);
            shoppingCartService.updateById(cart);

        }
        return R.success("添加成功");

    }
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(ShoppingCart shoppingCart){
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }
    @DeleteMapping("/clean")
    public R<String> clean(ShoppingCart shoppingCart){
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
        return R.success("清空成功");
    }
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart){
        QueryWrapper<ShoppingCart> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("user_id", BaseContext.getCurrentId());
        queryWrapper1.eq(shoppingCart.getDishId()!=null,"dish_id",shoppingCart.getDishId());
        queryWrapper1.eq(shoppingCart.getSetmealId()!=null,"setmeal_id",shoppingCart.getSetmealId());
        ShoppingCart cart = shoppingCartService.getOne(queryWrapper1);
        cart.setNumber(cart.getNumber()-1);
        shoppingCartService.updateById(cart);
        if (cart.getNumber()<=0){
            shoppingCartService.removeById(cart.getId());
        }
            return R.success("减一成功");
    }

}
